package com.ywjt.platformbusiness.home;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.stx.xhb.xbanner.XBanner;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseVPFragment;
import com.ywjt.platformbusiness.base.MenuModel;
import com.ywjt.platformbusiness.classify.activity.ShopHomeDetailActivity;
import com.ywjt.platformbusiness.classify.activity.ShopListActivity;
import com.ywjt.platformbusiness.classify.model.FistLevelTypeModel;
import com.ywjt.platformbusiness.classify.model.HomeRecommonShopModel;
import com.ywjt.platformbusiness.classify.model.ShopListModel;
import com.ywjt.platformbusiness.constants.Constants;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.home.activity.ActivityCitySelect;
import com.ywjt.platformbusiness.home.activity.Activity_Search_History;
import com.ywjt.platformbusiness.home.activity.CouponDrawActivity;
import com.ywjt.platformbusiness.home.model.HomeRecommonGoods;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.market.commongoods.activity.Activity_GoodsDetail;
import com.ywjt.platformbusiness.market.hagglegoods.activity.HaggleMallActivity;
import com.ywjt.platformbusiness.home.adapter.HomeMenuAdapter;
import com.ywjt.platformbusiness.home.adapter.HomeRecommondAdapter;
import com.ywjt.platformbusiness.home.adapter.HomeRecommondStoreAdapter;
import com.ywjt.platformbusiness.market.integralgoods.activity.IntegralMallActivity;
import com.ywjt.platformbusiness.market.timelimitgoods.activity.TimeLimitGoodsActivity;
import com.ywjt.platformbusiness.message.MessageActivity;
import com.ywjt.platformbusiness.market.seckillgoods.activity.SeckillGoodsActivity;
import com.ywjt.platformbusiness.my.activity.ActivityInvest;
import com.ywjt.platformbusiness.util.JsonUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class HomeIndex extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private View view;
    private RecyclerView rcMenu,rcRecommond,rcRecommondSrore;
    private List<Integer> banners;
    private HomeMenuAdapter menuAdapter;
    private HomeRecommondAdapter recommondAdapter;
    private HomeRecommondStoreAdapter recommondStoreAdapter;
    private XBanner banner;
    private SmartRefreshLayout refresh;
    private ImageView ivMsg;
    private ImageView rlIntegralMall,rlHaggleMall,rlSeckill,rlTimeLimit,rlInvest,rlCoupon;
    private LinearLayout llSearch,llCity,llMore;
    private Integer currentPage=1;

    private List<MenuModel> menuModelList;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
           case  R.id.ivMsg:
                 MessageActivity.actionStart(context);
                break;
//            case R.id.llType:
//                EventBusBean busBean=new EventBusBean();
//                busBean.setCode(101);
//                EventBus.getDefault().post(busBean);
//                break;
            case R.id.rlIntegralMall:
                //积分商城
                IntegralMallActivity.actionStart(context);
                break;
            case R.id.rlHaggleMall:
                HaggleMallActivity.actionStart(context);
                break;
            case R.id.rlSeckill:
                SeckillGoodsActivity.actionStart(context);
                break;
            case R.id.rlTimeLimit:
                TimeLimitGoodsActivity.actionStart(context);
                break;
            case R.id.rlInvest:
                ActivityInvest.actionStart(context);
                break;
            case R.id.rlCoupon:
                CouponDrawActivity.actionStart(context);
                break;
            case R.id.llSearch:
                //全局搜索
                Activity_Search_History.actionStart(context);
                break;
            case R.id.llCity:
                //城市选择
                ActivityCitySelect.actionStart(context);
                break;
            case R.id.llMore:
                //推荐上架更多
                ShopListActivity.actionStart(context,"");
                break;
        }
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) { }

    @Override
    protected void onFragmentFirstVisible() { }

    public static HomeIndex newInstance(String content) {
        Bundle arguments = new Bundle();
        arguments.putString("string", content);
     HomeIndex fl = new HomeIndex();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.home_index, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        rcMenu=view.findViewById(R.id.rcMenu);
        rlInvest=view.findViewById(R.id.rlInvest);
        llCity=view.findViewById(R.id.llCity);
        banner=view.findViewById(R.id.banner);
        ivMsg=view.findViewById(R.id.ivMsg);
        llMore=view.findViewById(R.id.llMore);
        rlTimeLimit=view.findViewById(R.id.rlTimeLimit);
        rlSeckill=view.findViewById(R.id.rlSeckill);
        rlHaggleMall=view.findViewById(R.id.rlHaggleMall);
        rlIntegralMall=view.findViewById(R.id.rlIntegralMall);
        rcRecommondSrore=view.findViewById(R.id.rcRecommondSrore);
        rcRecommond=view.findViewById(R.id.rcRecommond);
        rlCoupon=view.findViewById(R.id.rlCoupon);
        refresh=view.findViewById(R.id.refresh);
        llSearch=view.findViewById(R.id.llSearch);
        ivMsg.setOnClickListener(this::onClick);
        rlTimeLimit.setOnClickListener(this::onClick);
        rlHaggleMall.setOnClickListener(this::onClick);
        rlIntegralMall.setOnClickListener(this::onClick);
        rlSeckill.setOnClickListener(this::onClick);
        rlInvest.setOnClickListener(this::onClick);
        rlCoupon.setOnClickListener(this::onClick);
        llSearch.setOnClickListener(this::onClick);
        llCity.setOnClickListener(this::onClick);
        llMore.setOnClickListener(this::onClick);
        banners=new ArrayList<>();
        banners.add(R.mipmap.icon_home_default_banner);
        banners.add(R.mipmap.icon_home_default_banner);
        banners.add(R.mipmap.icon_home_default_banner);
        banners.add(R.mipmap.icon_home_default_banner);


        banner.setData(R.layout.item_banner1,banners,null);
        banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object object, View view, int position) {
                RelativeLayout container=(RelativeLayout) view;
                ImageView ivBanner=container.findViewById(R.id.ivBanner);
                Glide.with(context).load(banners.get(position)).into(ivBanner);
            }
        });

        banner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object obj, View view, int position) { }
        });
        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) { }
        });

        setView();
        // 获取首页推荐商家列表
        getRecommonShop();
       //获取金刚区数据
       getData();

       //获取首页推荐商品列表
        getRecommondGoods();
    }

    //首页推荐商家列表
    private void getRecommonShop() {
        new HttpRequest(getContext()).doGet(UrlConstants.getRecommendShopList, "",new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), HomeRecommonShopModel.class);
                        if (obj instanceof HomeRecommonShopModel) {
                            HomeRecommonShopModel model=(HomeRecommonShopModel)obj;
                            recommondStoreAdapter=new HomeRecommondStoreAdapter(model.getResult());
                            rcRecommondSrore.setAdapter(recommondStoreAdapter);
                            rcRecommondSrore.setLayoutManager(new GridLayoutManager(context,2,RecyclerView.VERTICAL,false));
                            recommondStoreAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    ShopListModel.ResultDTO.RecordsDTO bean=new ShopListModel.ResultDTO.RecordsDTO();
                                    bean.setId(model.getResult().get(position).getId());
                                    bean.setAddress(model.getResult().get(position).getAddress());
                                    bean.setShopLogo(model.getResult().get(position).getShopLogo());
                                    bean.setDistance(model.getResult().get(position).getDistance());
                                    bean.setShopName(model.getResult().get(position).getShopName());
                                    ShopHomeDetailActivity.actionStart(context,bean);
                                }
                            });
                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }


    private int count=0;
    private List<HomeRecommonGoods.ResultDTO.RecordsDTO> datas;

    public void setView(){
        datas=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getRecommonShop();
                        getData();
                        getRecommondGoods();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getRecommondGoods();
                    }
                }, 1000);
            }
        });
    }


    //首页推荐商品列表
    private void getRecommondGoods() {
        JSONObject jsonObject=new JSONObject();

        try {
            jsonObject.put("pageNum",currentPage);
            jsonObject.put("pageSize", Constants.PAGESIZE);//
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(getContext()).doPost(UrlConstants.getRecommendCommdityList, "",jsonObject,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), HomeRecommonGoods.class);
                        if (obj instanceof HomeRecommonGoods) {
                            HomeRecommonGoods model=(HomeRecommonGoods)obj;
                            if (currentPage == 1) {
                                datas.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    datas=model.getResult().getRecords();
                                    rcRecommond.setVisibility(View.VISIBLE);

                                    rcRecommond.setLayoutManager(new GridLayoutManager(context,2,RecyclerView.VERTICAL,false));
                                    rcRecommond.setAdapter(recommondAdapter);

                                    recommondAdapter=new HomeRecommondAdapter(datas);
                                    rcRecommond.setLayoutManager(new GridLayoutManager(context,2,RecyclerView.VERTICAL,false));
                                    rcRecommond.setAdapter(recommondAdapter);

                                    recommondAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            Activity_GoodsDetail.actionStart(context,datas.get(position).getId(),"");
                                        }
                                    });

                                    if (recommondAdapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                } else {
                                    refresh.finishRefreshWithNoMoreData();
                                }
                            } else {
                                datas.addAll(model.getResult().getRecords());
                                recommondAdapter.notifyDataSetChanged();
                                if (recommondAdapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishRefresh();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishRefreshWithNoMoreData();
                                }
                            }
                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }


    //获取一级分类  金刚区
    public void getData(){
        new HttpRequest(getContext()).doGet(UrlConstants.getFirstClassify, "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), FistLevelTypeModel.class);
                        if (obj instanceof FistLevelTypeModel) {
                            FistLevelTypeModel levelTypeModel =(FistLevelTypeModel)obj;
                            if (levelTypeModel.getResult().size()>0){
                                menuModelList=new ArrayList<>();

                                if(levelTypeModel.getResult().size()>=7){
                                    for (int i=0;i<7;i++){
                                        MenuModel bean=new MenuModel(levelTypeModel.getResult().get(i).getId(),
                                                levelTypeModel.getResult().get(i).getPicture(),levelTypeModel.getResult().get(i).getName());
                                        menuModelList.add(bean);
                                    }
                                    MenuModel bean=new MenuModel("","","全部");
                                    menuModelList.add(bean);

                                }
                                menuAdapter=new HomeMenuAdapter(menuModelList);
                                rcMenu.setAdapter(menuAdapter);
                                rcMenu.setLayoutManager(new GridLayoutManager(context,4,RecyclerView.VERTICAL,false));
                                menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                        ShopListActivity.actionStart(context,menuModelList.get(position).getId());
                                    }
                                });
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}